package com.ebt.m.fragment;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.ebt.m.AppContext;
import com.ebt.m.R;
import com.ebt.m.activity.MainActivity;
import com.ebt.m.activity.WebBaseActivity;
import com.ebt.m.commons.buscomponent.permission.RxPermissions;
import com.ebt.m.commons.utils.ActivityUtils;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.customer.util.PhoneUtil;
import com.ebt.m.data.bean.UserInfo;
import com.ebt.m.data.event.EPageOperate;
import com.ebt.m.event.WaitDialogEvent;
import com.ebt.m.policy.ActChoosePolicy;
import com.ebt.m.proposal_v2.widget.dialog.EBTProgressDialog;
import com.ebt.m.utils.ConfigData;
import com.ebt.m.utils.UIHelper;
import com.ebt.m.utils.UriUtils;
import com.ebt.m.utils.js.JsObject;
import com.ebt.m.utils.js.JsObjectCustomeA;
import com.jakewharton.rxbinding2.view.RxView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import static android.app.Activity.RESULT_OK;
import static com.ebt.m.activity.WebBaseActivity.WEB_TYPE_TOP_BACK_TO_MAIN;

/**
 * 包含webview的fragment
 *
 * @author Andy.Wang
 */
public class WebBaseFragment extends Fragment implements WebBaseActivity.OnBackListener {
    protected int mCurrentType;
    protected String link;
    protected WebView mWebView;
    protected View netError;
    protected View serverError;
    protected ProgressBar mProgressBar;
    protected UserInfo mCurrentUser;
    protected WebSettings settings;
    protected VideoWebChromeClient client = new VideoWebChromeClient();
    private JsObject jsObject = null;
    private JsObjectCustomeA jsObjectA = null;

    private String mCM;
    private ValueCallback<Uri> mUM;
    private ValueCallback<Uri[]> mUMA;
    private final static int FCR = 9999;
    private File realPhotoFile = null;
    private boolean isTopBackToMain = false;

    private FrameLayout fullVideo;
    private View customView = null;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mCurrentUser = AppContext.getCurrentUser();
        setHasOptionsMenu(true);
        EventBus.getDefault().register(this);
        Bundle bundle = getArguments();
        mCurrentType = bundle.getInt(WebBaseActivity.WEB_TYPE_FRAGMENT);
        if (bundle.containsKey(WebBaseActivity.WEB_TYPE_LINK)) {
            link = bundle.getString(WebBaseActivity.WEB_TYPE_LINK);
        }
        if (bundle.containsKey(WEB_TYPE_TOP_BACK_TO_MAIN)) {
            isTopBackToMain = bundle.getBoolean(WEB_TYPE_TOP_BACK_TO_MAIN);
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.view_web_base, container, false);
        this.netError = view.findViewById(R.id.no_net_container);
        this.serverError = view.findViewById(R.id.net_slow_container);
        this.mWebView = (WebView) view.findViewById(R.id.webview);
        this.mProgressBar = (ProgressBar) view.findViewById(R.id.loading);
        fullVideo = view.findViewById(R.id.full_video);
        settings = mWebView.getSettings();
        settings.setSupportZoom(false);
        settings.setAllowFileAccess(true);
        settings.setPluginState(WebSettings.PluginState.ON_DEMAND);
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setLoadsImagesAutomatically(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setTextZoom(100);
        mWebView.setWebChromeClient(client);
        mWebView.setWebViewClient(new MyWebViewClient());
        setJSInterface();
        RxView.clicks(this.netError.findViewById(R.id.load_refresh_net))
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    mWebView.reload();
                    toggleBarDisplayStatus(false);
                    hideFailView();
                    if (mWebView.getVisibility() == View.GONE) {
                        mWebView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mWebView.setVisibility(View.VISIBLE);
                            }
                        }, 500);
                    }
                });
        RxView.clicks(this.serverError.findViewById(R.id.load_refresh))
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    mWebView.reload();
                    toggleBarDisplayStatus(false);
                    hideFailView();
                    if (mWebView.getVisibility() == View.GONE) {
                        mWebView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mWebView.setVisibility(View.VISIBLE);
                            }
                        }, 500);
                    }
                });
        return view;
    }

    protected void setJSInterface() {
        jsObject = new JsObject(getContext(), mWebView);
        jsObjectA = new JsObjectCustomeA(getContext(), mWebView);
        mWebView.addJavascriptInterface(jsObject, "EbtJsBridge");
        mWebView.addJavascriptInterface(jsObjectA, "__EBAO_JSSDK");
        jsObject.registerForEventBus();
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        loadData();
    }

    protected void loadData() {
        String url = createUrl();
        mWebView.postDelayed(new Runnable() {

            @Override
            public void run() {
                mWebView.loadUrl(url);
            }
        }, 100);
        mProgressBar.setVisibility(View.VISIBLE);

    }

    /**
     * 隐藏错误view
     */
    private void hideFailView() {
        netError.setVisibility(View.GONE);
        serverError.setVisibility(View.GONE);
    }

    /**
     * 显示错误view
     *
     * @param type
     */
    private void showFailView(int type) {
        if (type == 1) {
            Toast.makeText(getActivity(), getResources().getString(R.string.network_fail), Toast.LENGTH_SHORT).show();
            netError.setVisibility(View.VISIBLE);
            serverError.setVisibility(View.GONE);
        } else if (type == 2) {
            netError.setVisibility(View.GONE);
            serverError.setVisibility(View.VISIBLE);
        }
        mWebView.stopLoading();
        mWebView.clearView();
        mWebView.setVisibility(View.GONE);
        //出现错误页面时，如果bar没有显示则显示
        if (netError.getVisibility() == View.VISIBLE || serverError.getVisibility() == View.VISIBLE) {
            toggleBarDisplayStatus(true);
        }
    }

    /**
     * 隐藏或者显示toolbar
     *
     * @param show
     */
    private void toggleBarDisplayStatus(boolean show) {
        if (getActivity() instanceof WebBaseActivity) {
            WebBaseActivity webBaseActivity = (WebBaseActivity) getActivity();
            android.support.v7.app.ActionBar actionBar = webBaseActivity.getSupportActionBar();
            if (actionBar == null) {
                return;
            }
            if (show) {
                if (!actionBar.isShowing()) {
                    actionBar.show();
                }
            } else {
                if (actionBar.isShowing()) {
                    actionBar.hide();
                }
            }
        }
    }

    protected void showFail(int errorCode) {
        Logger.e("errorCode = " + errorCode);
        mProgressBar.setVisibility(View.GONE);
//        if (mWebView.canGoBack()) {
//            return;
//        }
        int type = 0;//网络不可用
        switch (errorCode) {
            case WebViewClient.ERROR_HOST_LOOKUP://网络不通
                type = 1;
                break;
            case WebViewClient.ERROR_TIMEOUT:// /** Connection timed out */
                type = 2;
                break;
            case WebViewClient.ERROR_CONNECT:///** Failed to connect to the server */
                type = 1;
                break;
            case WebViewClient.ERROR_IO://    /** Failed to read or write to the server */
                type = 2;
                break;
            default://默认加载失败
//                loadFail.setErrorType(EBTErrorView.ErrorType.LOAD_ERROR);
                break;
        }
        showFailView(type);
    }

    protected String createUrl() {
        if (TextUtils.isEmpty(link)) {
            Toast.makeText(getActivity(), "缺少相关参数，打开链接失败", Toast.LENGTH_SHORT).show();
            getActivity().finish();
            return null;
        } else {
            return link;
        }
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    public boolean onBackPressed() {
        if (mWebView == null) {
            return false;
        }
        if (jsObject != null) {
            String pUrl = (String) jsObject.getResultMap().get("titleUrl");
            String methodName = (String) jsObject.getResultMap().get("methodName");
            if (mWebView != null && pUrl != null && !mWebView.getUrl().equalsIgnoreCase(pUrl)) {
                mWebView.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        mWebView.loadUrl(pUrl);
                    }
                }, 100);
                return true;
            }
            if (mWebView != null && methodName != null && methodName.length() > 0) {
                Logger.e("执行自定义方法:" + methodName);
                mWebView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mWebView.loadUrl("javascript:" + methodName + "()");
                    }
                }, 100);
                return true;
            }
        }
        if (jsObjectA != null) {
//            mWebView.loadUrl("javascript:alert((typeof onAndroidReturn != 'undefined'&& onAndroidReturn instanceof Function)?onAndroidReturn():false)");
            mWebView.evaluateJavascript("javascript:((typeof onAndroidReturn != 'undefined'&& onAndroidReturn instanceof Function)?onAndroidReturn():false)", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    //此处为 js 返回的结果
                    Logger.e(value);
                    if (value.equalsIgnoreCase("false")) {
                        if (mWebView != null && mWebView.canGoBack()) {
                            mWebView.goBack();
                        } else {
                            getActivity().finish();
                            if (isTopBackToMain) {
                                ActivityUtils.launchActivity(getActivity(), MainActivity.class);
                            }
                        }
                    }
                }
            });
        }
        return true;
    }

    class VideoWebChromeClient extends WebChromeClient {


        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            Log.w("WebBaseFragment", "--onProgressChanged:" + newProgress);
            if (newProgress == 100) {
                mProgressBar.setVisibility(View.GONE);
            } else {
                if (newProgress <= 10 && jsObject != null) {
                    jsObject.getResultMap().clear();
                }
                if (mProgressBar.getVisibility() == View.VISIBLE) {
                    mProgressBar.setProgress(newProgress);
                }
            }
            super.onProgressChanged(view, newProgress);
        }

        // For Lollipop 5.0+ Devices
        @Override
        public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {

            RxPermissions rxPermissions = new RxPermissions((Activity) getContext());
            rxPermissions.request(Manifest.permission.CAMERA)
                    .subscribe(permission -> {
                        if (permission) {
                            if (mUMA != null) {
                                mUMA.onReceiveValue(null);
                            }
                            mUMA = filePathCallback;
                            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {

                                try {
                                    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                                    String imageFileName = "img_" + timeStamp + "_";
                                    File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                                    if (!storageDir.exists()) {
                                        storageDir.mkdirs();
                                    }
                                    realPhotoFile = File.createTempFile(imageFileName, ".png", storageDir);
                                    takePictureIntent.putExtra("PhotoPath", mCM);
                                } catch (IOException ex) {
                                    ex.printStackTrace();
                                }
                                if (realPhotoFile != null) {
                                    mCM = "file:" + realPhotoFile.getAbsolutePath();
                                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(realPhotoFile));
                                } else {
                                    takePictureIntent = null;
                                }
                            }
                            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
                            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
                            contentSelectionIntent.setType("image/*");
                            Intent[] intentArray;
                            if (takePictureIntent != null) {
                                intentArray = new Intent[]{takePictureIntent};
                            } else {
                                intentArray = new Intent[0];
                            }
                            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                                chooserIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            }
                            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
                            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
                            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
                            if (jsObject.getResultMap().containsKey("openCamera")) {
                                startActivityForResult(takePictureIntent, FCR);
                            } else {
                                startActivityForResult(chooserIntent, FCR);
                            }
                        } else {
                            UIHelper.makeToast(getContext(), "请在设置中为" + getContext().getResources().getString(R.string.app_name) + "开启相机权限");
                        }
                    });
            return true;
        }

        // For Android > 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mUM = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            startActivityForResult(Intent.createChooser(i, "File Chooser"), FCR);
        }

        // Andorid 3.0 +
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            mUM = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            startActivityForResult(Intent.createChooser(i, "File Browser"), FCR);
        }

        // Android 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            mUM = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            startActivityForResult(Intent.createChooser(i, "File Chooser"), FCR);
        }

        //
//        @Override
//        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
//            Logger.e(message);
//            if (message!=null&&message.equalsIgnoreCase("false")){
//                if (mWebView != null && mWebView.canGoBack()) {
//                    mWebView.goBack();
//                    return true;
//                }else {
//                    result.confirm();
//                    getActivity().finish();
//                }
//            }else {
//                result.confirm();
//                return true;
//            }
//            return false;
//        }
        @Override
        public void onHideCustomView() {

            if (customView == null) {
                return;
            }
            fullVideo.removeView(customView);
            fullVideo.setVisibility(View.GONE);
            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);//清除全屏

        }

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            customView = view;
            fullVideo.setVisibility(View.VISIBLE);
            fullVideo.addView(customView);
            fullVideo.bringToFront();
            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏
        }
    }

    class MyWebViewClient extends WebViewClient {
        protected static final String TAG = "WebView ImageLoader";
        protected boolean loadingfinished = true;
        protected boolean redirect = false;

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            loadingfinished = false;
            super.onPageStarted(view, url, favicon);
            Log.w("WebBaseFragment", "--onPageStarted");
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            return super.shouldInterceptRequest(view, url);
        }

        boolean consumeTenPay = false;

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.w("WebBaseFragment", "--shouldOverrideUrlLoading--old");
            if (url == null) {
                return false;
            }
            if (!loadingfinished) {
                redirect = true;
            }

            loadingfinished = false;

            if (url.contains("wx.tenpay.com")) { //处理微信支付H5外起没有refer的问题
                return configWeiXinPay(url);
            } else if (url.startsWith("weixin://") || url.startsWith("alipays://")) { // 调起微信支付宝
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
                return true;
            } else if (url.startsWith("tel:")) { //拨打电话
                PhoneUtil.callPhone(getActivity(), Uri.parse(url));
                return true;
            } else if (url.contains("wifi") && url.contains("url=")) { //360wifi拦截网址出现广告
                mWebView.postDelayed(() -> {
                    try {
                        mWebView.loadUrl(processUrl(url));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }, 100);
                return true;
            } else { //不处理交由系统处理，解决重定向与goback()的冲突
                return false;
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            Log.w("WebBaseFragment", "--shouldOverrideUrlLoading--new");
            return super.shouldOverrideUrlLoading(view, request);
        }

        private boolean configWeiXinPay(String url) {
            if (consumeTenPay) {
                consumeTenPay = false;
                return false;
            }
            try {
                String newUrl = URLDecoder.decode(processUrl(url), "UTF-8");
                String prop = URLDecoder.decode(ConfigData.WX_PAY_URL, "UTF-8");

                mWebView.post(new Runnable() {
                    @Override
                    public void run() {
                        mWebView.loadDataWithBaseURL(prop, "<script>\n" +
                                "    window.location.href=\"" + newUrl + "\";\n" +
                                "    </script>", "text/html", "UTF-8", null);
                        consumeTenPay = true;
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (!redirect) {
                loadingfinished = true;
            }
            if (loadingfinished && !redirect) {
                mProgressBar.setVisibility(View.GONE);
            } else {
                redirect = false;
            }
//            showOrHideToolBar(false);
        }

        @Override
        // 新版本，只会在Android6及以上调用
        @TargetApi(Build.VERSION_CODES.M)
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            Logger.e("onReceivedError");
            // 或者：if(request.getUrl().toString() .equals(getUrl()))
            if (request.isForMainFrame()) {
                // 在这里显示自定义错误页
                showFail(error.getErrorCode());
            }
        }

        /**
         * 旧API在新API中也会被调用
         *
         * @param view
         * @param errorCode
         * @param description
         * @param failingUrl
         */
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                return;
            }
            showFail(errorCode);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            //handler.cancel(); 默认的处理方式，WebView变成空白页
            handler.proceed();//接受证书
            //handleMessage(Message msg); 其他处理
        }

    }


    /**
     * 屏蔽360wifi的拦截页面
     *
     * @param url
     * @return
     */
    private String processUrl(String url) {
        int urlstartIndex = url.indexOf("url=") + 4;
        url = url.substring(urlstartIndex);
        int urlendIndex = url.length();
        if (url.contains("&")) {
            urlendIndex = url.indexOf("&");
        }
        url = url.substring(0, urlendIndex);
        try {
            url = URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
        }
        return url;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        switch (itemId) {
            case android.R.id.home:
                getActivity().finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode,
                                 Intent intent) {
        if (Build.VERSION.SDK_INT >= 21) {
            Uri[] results = null;
            //Check if response is positive
            if (resultCode == RESULT_OK) {
                if (requestCode == FCR) {
                    if (null == mUMA) {
                        return;
                    }
                    if (intent == null || intent.getData() == null) {
                        //Capture Photo if no image available
                        if (mCM != null) {
                            if (realPhotoFile.length() > 2 * 1024 * 1024) {
                                results = new Uri[]{compressPic(Uri.parse(mCM))};
                            } else {
                                results = new Uri[]{Uri.parse(mCM)};
                            }
                        }
                    } else {
                        String dataString = intent.getDataString();
                        if (dataString != null) {
                            if (realPhotoFile.length() > 2 * 1024 * 1024) {
                                results = new Uri[]{compressPic(Uri.parse(dataString))};
                            } else {
                                results = new Uri[]{Uri.parse(dataString)};
                            }
                        }
                    }
                }
            }
            mUMA.onReceiveValue(results);
            mUMA = null;
        } else {
            if (requestCode == FCR) {
                if (null == mUM) {
                    return;
                }
                Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
                Uri u = compressPic(result);
                mUM.onReceiveValue(u);
                mUM = null;
            }
        }

    }

    private Uri compressPic(Uri uri) {
        ContentResolver contentResolver = getActivity().getContentResolver();
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        int newWidth = 200;
        float ratioX = newWidth / (float) bitmap.getWidth();
        int newHeight = (int) ((float) bitmap.getHeight() * ratioX);
        Bitmap scaledBitmap = Bitmap.createBitmap(newWidth, newHeight,
                Bitmap.Config.ARGB_8888);

        float middleX = newWidth / 2.0f;
        float middleY = newHeight / 2.0f;

        Matrix scaleMatrix = new Matrix();
        scaleMatrix.setScale(ratioX, ratioX, middleX, middleY);

        Canvas canvas = new Canvas(scaledBitmap);
        canvas.setMatrix(scaleMatrix);
        canvas.drawBitmap(bitmap, middleX - bitmap.getWidth() / 2, middleY
                - bitmap.getHeight() / 2, new Paint(
                Paint.FILTER_BITMAP_FLAG));

        String resizedFileName = "ImageResized.png";
        File sdCard = Environment.getExternalStorageDirectory();
        File dir = new File(sdCard.getAbsolutePath());
        File fileDir = new File(dir, resizedFileName);

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(fileDir);
            scaledBitmap.compress(Bitmap.CompressFormat.PNG, 80, fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Uri uriResult = UriUtils.getUriFromFile(fileDir);
        return uriResult;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            mWebView.removeAllViews();
            mWebView.destroy();
            mWebView = null;
        }
        EventBus.getDefault().unregister(this);
        if (jsObject != null) {
            jsObject.unregisterForEventBus();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventNetChanged(WaitDialogEvent event) {
        if (event.show) {
            showProgressDialog();
        } else {
            cancelProgress();
        }
    }

    /**
     * 显示progress dialog
     */
    private EBTProgressDialog mProgressDialog;

    private void showProgressDialog() {
        mProgressDialog = getEBTProgressDialog();
        mProgressDialog.setCanceledOnTouchOutside(false);
        if (!mProgressDialog.isShowing()) {
            mProgressDialog.show();
        }
    }

    private EBTProgressDialog getEBTProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new EBTProgressDialog(getContext());
        }
        return mProgressDialog;
    }

    public void cancelProgress() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
        mProgressDialog = null;
    }


    /**
     * @return void 用来操作当前页面
     * @Description: 订阅参数传递
     * @throw
     */
    @Subscribe
    public void onEvent(EPageOperate params) {
        if (params == null || TextUtils.isEmpty(params.from)) {
            return;
        }
        if (params.from.equalsIgnoreCase(ActChoosePolicy.class.getName())) {
            refreshCurrentPage();
        }

    }

    public void refreshCurrentPage() {
        if (mWebView != null) {
            mWebView.post(new Runnable() {
                @Override
                public void run() {
                    mWebView.reload();
                }
            });
        }
    }
}
